<template>
  <div style="width:100%;">
    <div class="query-form">
      <el-form ref="queryForm" :inline="true" :model="data_query_form">
        <el-form-item label="供应商产品编码：" prop="productCode">
          <el-input
            v-model="data_query_form.productCode"
            type="text"
            placeholder="供应商产品编码"
          />
        </el-form-item>
        <el-form-item label="产品名称(中)：" prop="productName">
          <el-input
            v-model="data_query_form.productName"
            type="text"
            placeholder="产品名称(中)"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="queryFormReset">重置</el-button>
          <el-button type="primary" @click="queryFormQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="header-info" style="margin-top:40px;">
      <p>
        <span style="font-size:20px;font-weight:900;"
          >产品线：{{ query.formData.curProductLineName }}</span
        >
        <span style="color:red;margin-left:20px;"
          >注：可用量=库存量 - 占用量</span
        >
      </p>
    </div>
    <div class="product-list">
      <el-editable
        ref="productsList"
        v-loading="productTableLoading"
        height="400"
        :need-pagination="true"
        :columns="data_product_list.columns"
        :payload="data_product_list.data"
        :static-store="store"
        @reload="reloadData"
        @select="curSelect"
        @select-all="onSelectAll"
      />
    </div>
  </div>
</template>

<script>
/* eslint-disable no-plusplus */
import ElEditable from '@components/el-editable';
import { distributeSelectSaleProductList } from '@api/m_mall_web_v1.js';
import { isObject, compact } from 'lodash';
// eslint-disable-next-line import/extensions
import { SALES_PRODUCTS_COLUMNS } from './product.const.js';

export default {
  name: 'ProductAddDialogProductListComponent',
  components: { ElEditable },
  props: {
    type: {
      type: String,
      default: 'default'
    },
    query: {
      type: Object,
      default() {
        return {};
      }
    },
    fetcher: {
      type: Function,
      default() {}
    },
    // eslint-disable-next-line vue/require-default-prop
    store: null
  },
  data() {
    return {
      data_query_form: {
        productCode: '',
        productName: '',
        productLineCode: ''
      },
      data_product_list: {
        storageProducts: [],
        data: {},
        columns: SALES_PRODUCTS_COLUMNS
      },
      page: 1,
      selectedProducts: [],
      productTableLoading: false
    };
  },
  created() {
    this.setInitDataAndGetFirstData();
  },
  methods: {
    // 初始化搜索条件并请求初始化接口数据
    setInitDataAndGetFirstData() {
      // 写死产品线搜索条件的值
      this.data_query_form.productLineCode = this.query.formData.create.contract;
      this.reloadData({ number: 1, size: 20 });
    },
    reloadData(pager) {
      // 切换分页时，存储数据
      this.productTableLoading = true;
      this.page = pager.number;
      this.fetcher({
        url: distributeSelectSaleProductList,
        method: 'post',
        data: {
          page: pager.number,
          pageSize: pager.size,
          productCode: this.data_query_form.productCode,
          productLineCode: this.data_query_form.productLineCode,
          productName: this.data_query_form.productName,
          // orderDate: this.query.formData.sales_info.date,
          saleTargetCode: this.query.formData.sales_info.target,
          supplierCode: this.query.formData.create.supplier
        }
      })
        .then(res => {
          const result = isObject(res.data.payload) ? res.data.payload : [];
          this.data_product_list.data = result;
          this.data_product_list.data.content = this.data_product_list.data.content.map(
            item => ({
              mixsIds:
                item.productCode + item.batchNo + item.seqNo + item.validDate,
              ...item,
              referencePrice: 0
            })
          );
          this.data_product_list.data.content.forEach(item => {
            const newItem = item;
            newItem.stockCount = parseFloat(item.stockCount);
            newItem.occupyCount = parseFloat(item.occupyCount);
            newItem.availableCount = parseFloat(item.availableCount);
          });
          if (this.data_product_list.storageProducts.length > 0) {
            this.reActiveListRows();
          }
        })
        .finally(() => {
          this.productTableLoading = false;
        });
    },
    reActiveListRows() {
      const curPageRow = this.data_product_list.storageProducts;
      if (curPageRow && curPageRow.length > 0) {
        curPageRow.forEach(item => {
          const findItem = this.data_product_list.data.content.find(
            it => it.mixsIds === item.mixsIds
          );
          if (findItem) {
            this.$nextTick(() => {
              this.$refs.productsList.$refs.table.toggleRowSelection(
                findItem,
                true
              );
            });
          }
        });
      }
    },
    queryFormReset() {
      this.$refs.queryForm.resetFields();
      this.queryFormQuery();
    },
    queryFormQuery() {
      this.reloadData({ number: 1, size: 20 });
    },
    deDuplication(curSelectedProducts) {
      this.data_product_list.storageProducts = this.data_product_list.storageProducts.concat(
        curSelectedProducts
      );
      this.data_product_list.storageProducts = this.uniqueDoubleCycle(
        this.data_product_list.storageProducts,
        'mixsIds'
      );
      return this.data_product_list.storageProducts;
    },
    onSelectAll(selection) {
      // 如果有数据，说明是全选选中状态，那么把所有的数据放入storageProducts并去重
      if (selection.length) {
        this.data_product_list.storageProducts = this.deDuplication(
          this.data_product_list.storageProducts.concat(
            this.data_product_list.data.content
          )
        );
      } else {
        // 如果没数据，就把当前页this.data_product_list.data的数据从storageProducts挨个删除
        // 即从存储的产品池中，删除当前已取消的产品（因为是全选操作，所以已取消的产品，即当页所有产品）
        this.data_product_list.storageProducts.forEach((item, index) => {
          const findItem = this.data_product_list.data.content.find(
            it => it.mixsIds === item.mixsIds
          );
          if (findItem) {
            // 猜猜这里为啥用undefined占位？
            // 因为如果删除了位置后，下标就变了，这里以下标作为标识
            this.data_product_list.storageProducts.splice(index, 1, undefined);
          }
        });
      }
      // 数组去空
      this.data_product_list.storageProducts = compact(
        this.data_product_list.storageProducts
      );
      // 因为全选的时候，我拿的是所有列表的数据，这里手动把availableCount小于等于0的数据删掉
      // 个人觉得这样的逻辑不太好，这里由于项目已经基本完善，改动很大，暂时这样处理吧
      this.data_product_list.storageProducts = this.data_product_list.storageProducts.filter(
        item => item.availableCount > 0
      );
      this.$emit('selectionChange', this.data_product_list.storageProducts);
    },
    curSelect(selection, row) {
      // 判断当前是选中还是取消,true是选中，false是取消
      const flag =
        selection.findIndex(item => item.mixsIds === row.mixsIds) !== -1;
      // 是否存在于相应的数据中
      const storageIdx = this.data_product_list.storageProducts.findIndex(
        item => item.mixsIds === row.mixsIds
      );
      if (flag) {
        // 如果是增加，就一股脑把当前所有选中的selection都放进storageProducts，然后再去重
        this.data_product_list.storageProducts = this.deDuplication(
          this.data_product_list.storageProducts.concat(selection)
        );
      } else {
        // 如果是减少，那么直接删除在storageProducts中对应下标的数据
        this.data_product_list.storageProducts.splice(storageIdx, 1);
      }
      this.$emit('selectionChange', this.data_product_list.storageProducts);
    },
    // 去重算法
    uniqueDoubleCycle(array, key) {
      const newArr = [];
      const len = array.length;
      let isRepeat;

      for (let i = 0; i < len; i++) {
        // 第一次循环
        isRepeat = false;
        for (let j = i + 1; j < len; j++) {
          // 第二次循环
          if (array[i][key] === array[j][key]) {
            isRepeat = true;
            break;
          }
        }
        if (!isRepeat) {
          newArr.push(array[i]);
        }
      }
      return newArr;
    }
  }
};
</script>

<style lang="less" scoped>
.product-list {
  display: flex;
  flex: 1;
  .pagination {
    text-align: right;
    margin-top: 20px;
  }
}
</style>
